package com.mg.axechen.libnetwork

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch

class CoroutinesViewModel : ViewModel() {

    val api by lazy { RetrofitManger.getApiService() }
    var articlesLiveData: MutableLiveData<MutableList<ArticleBean>> = MutableLiveData()

    var apiError:MutableLiveData<Throwable> = MutableLiveData()

    fun getArticles(page: Int) {

        val exception = CoroutineExceptionHandler { coroutineContext, throwable ->
            apiError.postValue(throwable)
            Log.i("CoroutinesViewModel",throwable.message!!)
        }

        viewModelScope.launch(exception) {
            val respose = api.getArticleList(page)
            if (respose.info == 0) {
                articlesLiveData.postValue(respose.data?.datas)
            } else {
                articlesLiveData.postValue(mutableListOf())
            }
        }
    }

}